import React from "react";
import routeWithUserSession from "@/components/ApplicationArea/routeWithUserSession";
import PageHeader from "@/components/PageHeader";
import { ControllerType } from "@/components/items-list/ItemsList";
import { BrowserRouter as Router,Link } from 'react-router-dom';//
import Button from "antd/lib/button";
import Col from "antd/lib/col";
import Divider from "antd/lib/divider";
import Form from "antd/lib/form";
import Input from "antd/lib/input";
import Table from "antd/lib/table";
import ConfigProvider from "antd/lib/config-provider";
import Layout from "antd/lib/layout";
import Tree from "antd/lib/tree";
import Modal from "antd/lib/modal";
import Row from "antd/lib/row";
import zhCN from 'antd/es/locale/zh_CN';
import Attaches from "@/services/attaches";
// import { createHashHistory } from 'history';
// const hashHistory = createHashHistory();
import {createBrowserHistory} from 'history'
import Enums from "@/services/enums";
import {currentUser} from "@/services/auth";
import routes from "@/services/routes";
import {WarningOutlined,SecurityScanTwoTone,DownOutlined,CarryOutOutlined, FormOutlined} from "@ant-design/icons";
import notification from "@/services/notification";
import {get} from "lodash";
const { confirm } = Modal;
const customHistory = createBrowserHistory();

const { Sider } = Layout;

class AttachesList extends React.Component {
  state = {
    page: 1,
    pagesize: localStorage.getItem("attacheslistpagesize") ? (localStorage.getItem("attacheslistpagesize") !== undefined ? Number(localStorage.getItem("attacheslistpagesize")) : 20) : 20,
    total:10,
    loading: false,
    annexname: '',
    contractcode: '',
    contractname: '',
    athdata: [],
    gData: [],
    selectedKeys: '',
    selectedTitle: '',
  };
  static propTypes = {
    controller: ControllerType.isRequired,
  };
    items=[{
      name:"cght",
      slug:"imgs",
      tags:"tags",
      is_draft:"df",
      is_archived:true
    }];
  componentWillMount() {
    this.loadData();
    let param={
      page: this.state.page,
      pagesize: this.state.pagesize,
      annexname: this.state.annexname,
      contractcode: this.state.contractcode,
      contractname: this.state.contractname,
      type: this.state.selectedKeys,
      userid: currentUser.id,
    }
    this.fetch(param);
  }
  fetch = (params = {}) => {
  //  this.setState({ loading: true });
    Attaches.getlistall(params).then(data => {
        this.setState({
            loading: false,
            athdata:data.data,
            page: params.page,
            pagesize: params.pagesize,
            total: data.total,
        });
    });
  };
  handlesel = () => {
    let param={
      page: 1,
      pagesize: this.state.pagesize,
      annexname: this.state.annexname,
      contractcode: this.state.contractcode,
      contractname: this.state.contractname,
      type: this.state.selectedKeys,
      userid: currentUser.id,
    }
    this.fetch(param);
  };
   handleTableChange = (pagination, filters, sorter) => {
    localStorage.setItem("attacheslistpagesize", pagination.pageSize);
    let field=sorter.field;
    let order=0;
    if(sorter.order==="descend"){
      order=1;
    }
    let param={
      field: field,
      order: order,
      page: pagination.current,
      pagesize: pagination.pageSize,
      annexname: this.state.annexname,
      contractcode: this.state.contractcode,
      contractname: this.state.contractname,
      type: this.state.selectedKeys,
      userid: currentUser.id,
    }
    this.fetch(param);
  };
  loadData=()=> {
    Enums.items("contract_enum").then(data => {
      const loop = (das, index) => {
        let items=[];
        das.forEach((item) => {
          item.icon= <SecurityScanTwoTone />;
          if (item.children) {
            item.children= loop(item.children, index+1);
          }
          items.push(item);
        });
        return items;
      };
      let datas=loop(data,0);
      this.setState({
        loading: false,
        gData: datas,
        selectedKeys: '',
        selectedTitle: '',
      });
    });
  }
  onSelect = (selectedKeys, e) => {
          let param={
            page: 1,
            pagesize: this.state.pagesize,
            annexname: this.state.annexname,
            contractcode: this.state.contractcode,
            contractname: this.state.contractname,
            type: selectedKeys[0],
            userid: currentUser.id,
          }
          this.fetch(param);
    // this.setState({
    //   selectedKeys: selectedKeys[0],
    //   selectedTitle: e.node.props.title,
    // });
};
handledown=record=>{
  let  filename=record.annexname;
  let AjaxUrl = 'api/upload/downloadfile';
  fetch(AjaxUrl ,{
   method: 'POST',
   body: window.JSON.stringify({filename: record.annexurl}),
   credentials: 'include',
   headers: new Headers({
     'Content-Type': 'application/json'
   })}).then((response) => {
   response.blob().then(blob => {
     const aLink = document.createElement('a');
     document.body.appendChild(aLink);
     aLink.style.display='none';
     const objectUrl = window.URL.createObjectURL(blob);
     aLink.href = objectUrl;
     aLink.download = record.annexname;
     aLink.click();
     document.body.removeChild(aLink);
   });
 }).catch((error) => {
  window.console.log(error);
 });
}
onDragEnter = info => {
  window.console.log(info);
  };
  render() {
    // const { currentPage } = this.state;
      const paginationProps = {
            showSizeChanger: true,
            // showQuickJumper: true,
            total: this.state.total, // 数据总数
            pageSize: parseInt(this.state.pagesize), // 每页条数
            current: parseInt(this.state.page), // 当前页码
            pageSizeOptions: ["10", "20", "30","100"],
            showTotal: ((total) => {
              return `共 ${total} 条`;
            }),
          };
      const listcolumns = [
      {
        title: '名称',
        dataIndex: 'annexname',
        key: 'annexname',
        sorter: (a, b) => a.annexname > b.annexname ? 1 : -1
      },
      {
        title: '编码',
        dataIndex: 'contractcode',
        key: 'contractcode',
        sorter: (a, b) => a.contractcode > b.contractcode ? 1 : -1
      },
      {
        title: '名称',
        dataIndex: 'contractname',
        key: 'contractname',
        sorter: (a, b) => a.contractname > b.contractname ? 1 : -1
      },
      {
        title: '分类',
        dataIndex: 'typename',
        key: 'typename',
        sorter: (a, b) => a.typename > b.typename ? 1 : -1
      },
      {
        title: '操作',
        key: 'action',
        render: (record) => (
          <span>
            <a className="clickable">
              {record.strstatus}
            </a>
            <Divider type="vertical" />
            <a className="clickable"  onClick={() => this.handledown(record)}>下载</a>
          </span>
        ),
      },
    ];
    return (
  <ConfigProvider locale={zhCN}>
      {/*<div className="page-dashboard-list">*/}
          <div  style={{width:"400px",height:"60px"}}>
            <div style={{width:"20px",height:"50px", float: "left"}}>
            </div>
              <div style={{width:"50px",height:"50px", float: "left"}}>
              <img src="/static/images/contractfinish.png" alt="HR" loading="lazy"/>
            </div>
              <div style={{width:"320px",height:"30px",float:"left"}}>
              <h3 style={{margin:"7px",padding:"0"}}>附件查询</h3>
            </div>
          </div>
      <Layout>
          <Layout>
            <Sider width={300} style={{ background: '#fff' }}>
              <Tree
                className="draggable-tree"
                draggable
                blockNode
                showIcon
                // showLine
                switcherIcon={<DownOutlined />}
                defaultExpandAll
                onDragEnter={this.onDragEnter}
                onSelect={this.onSelect}
                treeData={this.state.gData}
              />
            </Sider>
        <Layout style={{ padding: '0 24px 24px' }}>
      <Form layout="horizontal" {...{labelCol: { span: 4 }, wrapperCol: { span: 14 },} }>
          <Row>
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="附件名称">
              <Input
                value={this.state.annexname}
                onChange={e => this.setState({annexname:e.target.value})}
                placeholder="附件名称"
              />
						</Form.Item>
				  </Col>
        </Row>
          <Row>
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="编码">
              <Input
                value={this.state.contractcode}
                onChange={e => this.setState({contractcode:e.target.value})}
                placeholder="编码"
              />
            </Form.Item>
          </Col>
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="名称">
              <Input
                value={this.state.contractname}
                onChange={e => this.setState({contractname:e.target.value})}
                placeholder="名称"
              />
            </Form.Item>
				  </Col>
        </Row>
          <Row>
				  <Col span={10}>
          <Button type="primary" onClick={() => this.handlesel()} >
            <i className="fa fa-search m-r-5" />
            查询
          </Button>
				  </Col>
        </Row>
      </Form>
                 <div>
                      <Table rowKey='id'
                             columns={listcolumns}
                             dataSource={this.state.athdata}
                             pagination={paginationProps}
                             loading={this.state.loading}
                             onChange={this.handleTableChange}
                      />
                 </div>
        </Layout>
        </Layout>
       </Layout>
  </ConfigProvider>
    );
  }
}
routes.register(
  "Attaches.List",
  routeWithUserSession({
    path: "/attaches",
    title: "附件池",
    render: pageProps => <AttachesList {...pageProps}/>,
  })
);